package com.example.ai.controller;

import com.example.ai.entity.QARecord;
import com.example.ai.model.User;
import com.example.ai.repository.UserRepository;
import com.example.ai.service.QAService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/api/qa")
@RequiredArgsConstructor
@Slf4j
public class QAController {
    private final QAService qaService;
    private final UserRepository userRepository;

    @PostMapping("/ask")
    public ResponseEntity<QARecord> askQuestion(
            @RequestParam Long documentId,
            @RequestParam String question,
            @RequestParam String model,
            Authentication authentication) {
        Long userId = getUserIdFromAuthentication();
        QARecord qaRecord = qaService.askQuestion(documentId, question, model,userId);
        return ResponseEntity.ok(qaRecord);
    }

    @GetMapping("/history/document/{documentId}")
    public ResponseEntity<List<QARecord>> getDocumentQAHistory(
            @PathVariable Long documentId,
            Authentication authentication) {
        Long userId = getUserIdFromAuthentication();
        List<QARecord> history = qaService.getDocumentQAHistory(documentId, userId);
        return ResponseEntity.ok(history);
    }

    @GetMapping("/history")
    public ResponseEntity<List<QARecord>> getUserQAHistory(Authentication authentication) {
        Long userId = getUserIdFromAuthentication();
        List<QARecord> history = qaService.getUserQAHistory(userId);
        return ResponseEntity.ok(history);
    }

    @GetMapping(value = "/ask/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter askStream(
            @RequestParam Long documentId,
            @RequestParam String question,
            @RequestParam(defaultValue = "deepseek-chat") String model) {
            
        log.info("Received stream request - documentId: {}, question: {}", documentId, question);


        SseEmitter emitter = new SseEmitter(300000L);
        if(Objects.equals(model, "deepseek")){
            qaService.askStreamQuestionForDeepSeek(documentId, question, emitter);
        }else{
            qaService.askStreamQuestion(documentId, question, emitter);
        }

        return emitter;
    }

    private Long getUserIdFromAuthentication() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        return user.getId();
    }
} 